package com.ede.roverhu.simplebackstage.Activities;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;


import com.ede.roverhu.simplebackstage.Ibeacon.LeDeviceListAdapter;
import com.ede.roverhu.simplebackstage.Ibeacon.iBeaconClass;
import com.ede.roverhu.simplebackstage.R;
import com.ede.roverhu.simplebackstage.Utils.LogUtils;
import com.ede.roverhu.simplebackstage.Utils.ToastUtils;
import com.junkchen.blelib.BleService;


public class BlueToothActivity extends BaseActivity {

    //    private String[] strArr = new String[]{
//            "2F248B75-ADBF-B826-25A1-486220FB3A4C",//湖北交通学院
//            "E2C56DB5-DFFB-48D2-B060-D0F5A71096E0",//武汉工商学院
//            "26D516A0-1F4F-32A6-667F-BC815EF1E108"//武汉职业技术学院
//    };


    //private final static String UUID_KEY_DATA = "0000fff0-0000-1000-8000-00805f9b34fb";

    private final static int BLE_SUCCESS = 0x00;
    private final static int SERVICE_BIND = 0x01;
    private BleService mBleService;
    private boolean mIsBind;

    private ListView mlistview;
    private LeDeviceListAdapter mLeDeviceListAdapter;
    private BluetoothGatt mBluetoothGatt;
    private boolean mScanning = false;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == SERVICE_BIND)
                ToastUtils.show(getApplicationContext(), "服务已经开启");
        }
    };


    //绑定Service
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mBleService = ((BleService.LocalBinder) iBinder).getService();
            if (mBleService != null) mHandler.sendEmptyMessage(SERVICE_BIND);
            if (mBleService.initialize()) {
                if (mBleService.enableBluetooth(true)) {
                    mBleService.setOnLeScanListener(new OnLescanLinstener());
                    mScanning = true;
                    ToastUtils.show(BlueToothActivity.this, "蓝牙已开启");
                }
            } else {
                ToastUtils.show(BlueToothActivity.this, "蓝牙不支持");
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBleService = null;
            mIsBind = false;
        }
    };


    private void doBindService() {
        Intent serviceIntent = new Intent(this, BleService.class);
        bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private void doUnBindService() {
        if (mIsBind) {
            unbindService(serviceConnection);
            mBleService = null;
            mIsBind = false;
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blue_tooth);


        mlistview = (ListView) findViewById(R.id.listview);
        mLeDeviceListAdapter = new LeDeviceListAdapter(this);
        mlistview.setAdapter(mLeDeviceListAdapter);
        mlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                final iBeaconClass.iBeacon ibeacon = (iBeaconClass.iBeacon) mLeDeviceListAdapter.getItem(i);
                Intent intent = new Intent(BlueToothActivity.this, BlueToothInfoActivity.class);
                intent.putExtra("title", ibeacon.name);
                intent.putExtra("ibeacon", ibeacon.bluetoothAddress);
                startActivity(intent);


                LogUtils.e(ibeacon.bluetoothAddress);
            }
        });

        doBindService();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_bluetooth, menu);
        if (mScanning == true) {
            menu.getItem(0).setTitle("停止");
        } else {
            menu.getItem(0).setTitle("搜索");
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_scan) {
            if (mScanning == true) {
                mBleService.scanLeDevice(false);
                mScanning = false;
                item.setTitle("搜索");
            } else {
                mBleService.scanLeDevice(true);
                mScanning = true;
                item.setTitle("停止");
            }
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void onPause() {
        super.onPause();
        mBleService.scanLeDevice(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        doUnBindService();
    }


    private class OnLescanLinstener implements BleService.OnLeScanListener {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            final iBeaconClass.iBeacon ibeacon = iBeaconClass.fromScanData(device, rssi, scanRecord);
            if (ibeacon.major == 50002 && ibeacon.minor == 50417) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mLeDeviceListAdapter.addDevice(ibeacon);
                        mLeDeviceListAdapter.notifyDataSetChanged();
                    }
                });
            }
        }
    }
}
